<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { listPlant } from '@/api/dashboard'
const popup = ref(null)
const xData = ref([])
const yData = ref([])
function open() {
  popup.value.open()
  listPlant().then(res => {
    xData.value = []
    yData.value = []
    let data = res.rows
    for (let i = 0; i < data.length; i++) {
      xData.value.push(data[i].name)
      yData.value.push(data[i].gardenArea)
    }
    createEchart()
  })
}
async function createEchart(){
  await nextTick() // 确保DOM已经渲染完成
  chartInstance = echarts.init(plantChart.value)
  const option = {
    grid: {
      x: 70,
      y: 45
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: xData.value,
        axisLabel: {
          color: '#FFF',
          fontSize: 14,
          interval: 0 //代表显示所有x轴标签显示
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        offset: 10
      }
    ],
    yAxis: [
      {
        name: '亩',
        nameTextStyle: {
          //关键代码
          padding: [30, 0, 0, -30],
          color: '#FFF'
        },
        type: 'value',
        axisLabel: {
          color: '#FFF', //刻度线标签颜色
          fontSize: 14
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#2B3B46',
            width: 1
          }
        }
      }
    ],
    series: [
      {
        type: 'line',
        barWidth: '40%',
        data: yData.value,
        label: {
          position: 'top',
          formatter: '{c} 亩',
          fontSize: 13
        },
        symbolSize: 18,
        symbol: 'image:///api/profile/upload/assets/dot.png',
        areaStyle: {
          color: '#2495FD5F',
          opacity: 0.31
        },
        lineStyle: {
          width: 2,
          color: '#2392F8',
          shadowColor: '#16477C5F',
          shadowOffsetY: 4.5
        }
      }
    ]
  }
  chartInstance.setOption(option)
}
defineExpose({ open })
// 创建一个响应式引用来保存DOM元素
const plantChart = ref(null)
let chartInstance = null
// 销毁ECharts实例
onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose()
  }
})
</script>

<template>
  <Popup width="666" height="451.49" ref="popup" title="种植" type="small">
    <div ref="plantChart" style="width: 105%; height: 335px"></div>
  </Popup>
</template>

<style lang="scss" scoped></style>
